namespace Aurora.Discovery.HttpClient.Abstractions;

/// <summary>
/// http message handler discovery
/// </summary>
public class DiscoveryHttpMessageHandler : DelegatingHandler
{
    private readonly IDiscoveryClient _discoveryClient;

    public DiscoveryHttpMessageHandler(IDiscoveryClient discoveryClient)
    {
        _discoveryClient = discoveryClient;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        var service = await _discoveryClient.GetService(request.RequestUri.Host);

        if (!string.IsNullOrEmpty(service))
        {
            request.RequestUri = new Uri(new Uri(service), request.RequestUri.PathAndQuery);
        }

        return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
    }
}